package com.jijuxie.message.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jijuxie.message.domain.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {

    /**
     * 获取最新一条消息分组
     */
    @Select("SELECT m.* FROM chat_message m " +
            "INNER JOIN (" +
            "  SELECT " +
            "    MAX(t.send_time) as max_time, " +
            "    CASE WHEN t.from_user_id = #{userId} THEN t.to_user_id " +
            "         ELSE t.from_user_id END as other_user_id " +
            "  FROM chat_message t " +
            "  WHERE t.from_user_id = #{userId} OR t.to_user_id = #{userId} " +
            "  GROUP BY other_user_id" +
            ") as latest ON (" +
            "  (m.from_user_id = #{userId} AND m.to_user_id = latest.other_user_id) OR " +
            "  (m.to_user_id = #{userId} AND m.from_user_id = latest.other_user_id)" +
            ") AND m.send_time = latest.max_time " +
            "ORDER BY m.send_time DESC")
    List<ChatMessage> selectLastMessages(@Param("userId") Long userId);
}
